/*
 * Copyright (C) 2003-2009 eXo Platform SAS.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.reflext.core;

import org.reflext.api.ClassKind;
import org.reflext.api.ClassTypeInfo;
import org.reflext.api.annotation.AnnotationInfo;
import org.reflext.api.annotation.AnnotationType;
import org.reflext.spi.model.AnnotationModel;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

/**
 * @author <a href="mailto:julien.viet@exoplatform.com">Julien Viet</a>
 * @version $Revision$
 */
public class AnnotatedDelegate<T, M, A, P, E> extends ReflectedObject<T, M, A, P> {

  /** . */
  final AnnotationModel<T, E, A, P> annotationModel;

  /** . */
  private final E element;

  /** . */
  private Map<ClassTypeInfo, AnnotationInfo> annotations;

  public AnnotatedDelegate(
    TypeResolverImpl<T, M, A, P> domain,
    AnnotationModel<T, E, A, P> annotationModel,
    E element) {
    super(domain);

    //
    this.annotationModel = annotationModel;
    this.element = element;
  }

  public <AN> AN getDeclaredAnnotation(E element, AnnotationType<AN, ?> annotationType) {

    Object type = annotationType.getType();
    if (type instanceof Class<?>) {
      return (AN)annotationModel.resolveDeclaredAnnotation(element, (Class<Annotation>)type);
    } else if (type instanceof ClassTypeInfo) {
      ClassTypeInfo cti = (ClassTypeInfo)type;
      if (cti.getKind() != ClassKind.ANNOTATION) {
        throw new IllegalArgumentException("The provided class type info is not an annotation");
      }
      if (annotations == null) {
        Map<ClassTypeInfo, AnnotationInfo> annotations = new HashMap<ClassTypeInfo, AnnotationInfo>();
        for (A a : annotationModel.getDeclaredAnnotation(element)) {
          T ant = annotationModel.getAnnotationType(a);
          ClassTypeInfo aaaa = (ClassTypeInfo)domain.resolve(ant);
          annotations.put(aaaa, new AnnotationInfoImpl<T,M,A,P,E>(
            this,
            aaaa,
            a));
        }
        this.annotations = annotations;
      }
      return (AN)annotations.get(cti);
    } else {
      throw new AssertionError();
    }
  }
}
